﻿using System.Text;
using System.Security.Cryptography;
using WebStickyNotes.Contracts;

namespace WebStickyNotes.Helpers
{
    public static class EncryptionHelper
    {
        public static string HashString(string plainText)
        {
            string hashedText;

            if (plainText.Substring(0, 2).Equals("##"))
            {
                hashedText = plainText;
            }
            else
            {
                var textBytes = Encoding.Default.GetBytes(plainText);
                var cryptHandler = new MD5CryptoServiceProvider();
                var hashBytes = cryptHandler.ComputeHash(textBytes);
                var ret = string.Empty;
                foreach (byte a in hashBytes)
                {
                    if (a < 16)
                    {
                        ret += "0" + a.ToString("x");
                    }
                    else
                    {
                        ret += a.ToString("x");
                    }
                }
                hashedText = string.Format("##{0}", ret);
            }
            return hashedText;
        }

        public static bool ComparePassword(TaskPerson taskPerson, string attemptedPassword)
        {
            return HashString(attemptedPassword) == taskPerson.Password;
        }
    }
}